<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <object width="320" height="168"><param name="movie" value="http://www.lost4815162342.com/flash/countdown.swf"></param><param name="wmode" value="transparent"></param><embed src="http://www.lost4815162342.com/flash/countdown.swf" type="application/x-shockwave-flash" width="320" height="168" wmode="transparent"></embed></object>
        <BR>
        <?php
        include "ModelClass.php";



         class simple_profiler {

                private $start_time;

                private function get_time() {
                    list($usec, $seconds) = explode(" ", microtime());
                    return ((float)$usec + (float)$seconds);
                }
                function start_timer() {
                    $this->start_time = $this->get_time();
                }
                function end_timer() {
                    return ($this->get_time() - $this->start_time);
                }
            }

        //----------------------------------------------------------------------

        function conecta($dbhost,$dbusername,$dbpass,$database){
            $link=DB::connect($dbhost,$dbusername,$dbpass);
            if (!$link) {
                die('Could not connect: ' . mysql_error());
                return FALSE;
            }
            if(!DB::select_db($database,$link)){
                    DB::close($link);
                    die('Could not connect: ' . mysql_error());
                    return FALSE;
            }
            return $link;
        }

        //----------------------------------------------------------------------

        function reinicia(){
            $query= array(  'DROP TABLE data;',
                            'DROP TABLE structure;',
                            'DROP TABLE elements',
                            //Tabla estructura
                            "CREATE TABLE structure (
                                id INT(11) AUTO_INCREMENT PRIMARY KEY,
                                value VARCHAR(100) NOT NULL,
                                type VARCHAR(20) NOT NULL,
                                lft INT(6) NOT NULL,
                                rgt INT(6) NOT NULL
                            );",
                            //Indice sobre value
                            "CREATE UNIQUE INDEX IDX_STRUCT ON structure (value);",
                            //Tabla datos
                            "CREATE TABLE data(
                                id INT(11)NOT NULL,
                                id_structure INT(11)NOT NULL,
                                value VARCHAR(100)NOT NULL,
                                PRIMARY KEY(id,id_structure),
                                FOREIGN KEY (id_structure)
                                REFERENCES structure(id),
                                FOREIGN KEY (id)
                                REFERENCES elements(id)
                            );",
/*
                            "ALTER TABLE data ADD CONSTRAINT ref1
                            FOREIGN KEY (id) REFERENCES element(id);",

                            "ALTER TABLE data ADD CONSTRAINT ref2
                            FOREIGN KEY (id_structure) REFERENCES structure(id);",
*/
                            //sobra este indice (primary key index)
                            //"CREATE UNIQUE INDEX IDX_DATA ON data (id,id_structure);",
                            //Tabla elementos
                            "CREATE TABLE elements(
                                type CHAR(20),
                                id INT (11) AUTO_INCREMENT PRIMARY KEY ,
                                name VARCHAR(50)
                            );",
                            "CREATE INDEX IDX_ELEMENTS ON elements(name) "
                            );

            foreach ($query as $q) DB::query($q);

        }
        //----------------------------------------------------------------------

        function creaEstructura($model,$debug){
            //RAIZ
           // StructHandler::addChild('SISTEMA',"node","","");

            //PRIMER NIVEL
            $model->addChild('USR',"element","","",$debug);
            $model->addChild('RSC',"element","","",$debug);
            $model->addChild('HIS',"element#2","","",$debug);

            //SEGUNDO NIVEL
            $model->addChild('LOGIN',"node","/USR","",$debug);
            $model->addChild('GESTION',"node","","/USR/LOGIN",$debug);
            $model->addChild('ACTIVIDAD',"node","","/USR/GESTION",$debug);


            $model->addChild('LOCALIZACION',"node","/RSC","",$debug);
            $model->addChild('CATEGORIZACION',"node","/RSC","",$debug);

            $model->addChild('NOTA',"integer","/HIS","",$debug);
            $model->addChild('COMENTARIOS',"string","/HIS","",$debug);

            //TERCER NIVEL
            $model->addChild('USERNAME',"string","/USR/LOGIN","",$debug);
            $model->addChild('PASSWORD',"string","/USR/LOGIN","",$debug);

            $model->addChild('E_MAIL',"string","/USR/GESTION","",$debug);
            $model->addChild('NOMBRE_REAL',"string","/USR/GESTION","",$debug);

            $model->addChild('FECHA_REGISTRO',"date","/USR/ACTIVIDAD","",$debug);
            $model->addChild('ULTIMO_ACCESO',"date","/USR/ACTIVIDAD","",$debug);



            $model->addChild('PLATAFORMA',"string","/RSC/LOCALIZACION","",$debug);
            $model->addChild('ID_EXTERNO',"integer","/RSC/LOCALIZACION","",$debug);
            $model->addChild('ENTORNO_PROFESIONAL',"node","/RSC/CATEGORIZACION","",$debug);
            $model->addChild('ENTORNO_ACADEMICO',"node","/RSC/CATEGORIZACION","",$debug);

            //CUARTO NIVEL


            $model->addChild('AMBITO_LABORAL',"string","/RSC/CATEGORIZACION/ENTORNO_PROFESIONAL","",$debug);
            $model->addChild('SECTOR',"string","/RSC/CATEGORIZACION/ENTORNO_PROFESIONAL","",$debug);
            $model->addChild('PUESTOS_DE_TRABAJO',"string","/RSC/CATEGORIZACION/ENTORNO_PROFESIONAL","",$debug);
            $model->addChild('NIVEL',"integer","/RSC/CATEGORIZACION/ENTORNO_ACADEMICO","",$debug);
            $model->addChild('AREA_DE_CONOCIMIENTO',"string","/RSC/CATEGORIZACION/ENTORNO_ACADEMICO","",$debug);




            return true;
        }

        //----------------------------------------------------------------------

        function muestraArbol(){
            $result=DB::query("SELECT node.lft, node.rgt, node.type,CONCAT( REPEAT( '__', (COUNT(parent.value) - 1) ), node.value) AS value
                                FROM structure AS node,
                                structure AS parent
                                WHERE node.lft BETWEEN parent.lft AND parent.rgt
                                GROUP BY node.value
                                ORDER BY node.lft;");

            while ($r1=DB::fetch_assoc($result)){
                $fields= explode ('/',$r1['value']);
                $nc=count($fields);
                $n=array();
                for($i=0;$i<$nc-1;$i++){
                    $n[$i]=$fields[$i];
                }
                $n1=implode('/',$n);
                echo "<font color='#FF0000'>$n1</font>";
                echo "<font color='#0000CC'>/". $fields[$nc-1] ."</font>";
                echo "<font color='#339966'> ". $r1['type']."</font>";
                echo "<font color='#FF0000'> (".$r1['lft']."|".$r1['rgt'].") </font><BR>";
            }

        }
        
        // put your code here

        //CONEXION A LA BASE DE DATOS
$dbhost="localhost";
$dbusername="root";
$dbpass="";
$database="pruebas";
$debug=true;
//OPCIONES:
$reiniciar=true; //Borrar y crear tablas
$reiniciarEstructura=true;
$probar=true; //a falso no se hace la parte del codigo a probar




//CONEXION A BASE DE DATOS
$timer=new simple_profiler();
echo "1.-CONECTANDO A BASE DE DATOS ";
$timer->start_timer();
    $link=conecta($dbhost,$dbusername,$dbpass,$database);
$tiempo=$timer->end_timer();
echo " | CONECTADO: tiempo: $tiempo <BR>";

//CREAR OBJETO MODEL(despues de conectar, antes de modificar)
echo "2.-CREANDO OBJETO MODEL ";
$model=new Model($debug);
echo " | CREADO.";

//REINICIAR BASE DE DATOS
if($reiniciar){
    echo "3.-REINICIANDO BASE DE DATOS";
    $timer->start_timer();
        reinicia();
    $tiempo=$timer->end_timer();
    echo " | REINICIADA: tiempo: $tiempo<BR>";
}
$model->initializeStruct($debug);
if($reiniciarEstructura){
    echo "4.-CREANDO ESTRUCTURA DE ARBOL";
    $timer->start_timer();
        creaEstructura($model,$debug);
    $tiempo=$timer->end_timer();
    echo " | CREADA: tiempo: $tiempo<BR>";
}
echo "5.-SE MUESTRA EL ÁRBOL:<BR>";
muestraArbol();
echo "<BR><BR><BR><BR><BR>";

if($probar){



    echo "6.-CÓDIGO A PROBAR. MENSAJES DE DEPURACIÓN ";
    if($debug)echo "ACTIVADOS<BR>";
    else echo "DESACTIVADOS<BR>";

    //inicializacion de variables.
    $nombreE="";
    $tipoE="";
    $nombreV="";
    $valorV="";



    $model->addChild('ELEM1',"element","","",$debug);
    $model->addChild('ATRB1',"integer","/ELEM1","",$debug);
    $model->addChild('ERRONEO',"node","/ELEM1","",true);

    $model->addChild('ELEM2',"element","","",$debug);
    $model->addChild('ATRB1',"string","/ELEM2","",$debug);
    $model->addChild('NODOELEM',"element","/ELEM2","",true);
    $model->addChild('ATRB1',"integer","/ELEM2/NODOELEM","",true);
    
    $model->addChild('ELEM3',"element","","",$debug);
    $model->addChild('ATRB1',"integer","/ELEM3","",$debug);
    $model->addChild('ATRB1',"integer","/ELEM1","",$debug);
    $model->addChild('ATRB2',"string","/ELEM1","",$debug);
    
    $model->addChild('ELEM4',"element","","",$debug);
    $model->addChild('ATRB1',"integer","/ELEM4","",$debug);
    $model->addChild('ATRB2',"integer","/ELEM4","",$debug);
    
    $model->addChild('ELEM5',"tipoquenoeste","","",true);
    $model->addChild('ELEM6',"element#hgf","","",true);
    
    $model->addChild('REL2',"element#2","","",$debug);
    $model->addChild('ATR1',"integer","/REL2","",$debug);
    $model->addChild('REL3',"element#3","","",$debug);
    $model->addChild('ATR1',"integer","/REL3","",$debug);
    
    $model->addChild('REL4',"element#4","","",$debug);
    $model->addChild('NODO1',"integer","/REL4","",$debug);
    $model->addChild('NODO1',"integer","/REL4/NODO1","",$debug);
    $model->addChild('NODO2',"integer","/REL4/NODO1","",$debug);
    $model->addChild('NODO2',"integer","/REL4","",$debug);
    $model->addChild('NODO1',"integer","/REL4/NODO2","",$debug);
    $model->addChild('NODO1',"integer","/REL4/NODO2/NODO1","",$debug);
    $model->addChild('ATR1',"integer","/REL4/NODO2/NODO1/NODO1","",$debug);

    $model->addChild('REL22', 'element#2', "", "", $debug);
    $model->addChild('ATR1', 'integer', "/REL22", "", $debug);

    echo"<BR>Se muestra el árbol construído:<BR>";
    muestraArbol();
    echo"<BR><BR><BR><BR><BR>";

    echo "INSERTANDO ELEMENTOS SIMPLES.";
    $id1=array();
    $timer->start_timer();
        $id1[]=$model->insertElement('ELEM1',"ElementoTipo1",$debug);
        $id1[]=$model->insertElement('ELEM2',"ElementoTipo2",$debug);
        $id1[]=$model->insertElement('ELEM3',"ElementoTipo3",$debug);
        $id1[]=$model->insertElement('ELEM4',"ElementoTipo4",$debug);
        $id1[]=$model->insertElement('ELEM5',"ElementoTipo5",$debug);
        $id1[]=$model->insertElement('ELEM6',"ElementoTipo6",$debug);
    $tiempo=$timer->end_timer();
    echo " | TERMINADO. TIEMPO: $tiempo <BR>";
    echo " DETALLES DE LOS ELEMENTOS NO INSERTADOS:<BR>";
    $k=1;
    foreach ($id1 as $iddd){
        if($iddd<0) echo"EL ELEMENTO ElementoTipo$k de tipo ELEM$k no fue insertado <BR>";
        $k++;
    }

    echo "CREANDO RELACIONES ENTRE ELEMENTOS SIMPLES";
    $id2=array();
    $a="";
    $timer->start_timer();
        if ($model->insertElement('REL2',"ELEM1-1#ELEM2-2",$debug)<0)
            $a=$a."Elemento de REL2 NO FUE INSERTADO<BR>";
        if ($model->insertElement('REL3',"ELEM1-1#ELEM2-2#ELEM3-3",$debug)<0)
            $a=$a."Elemento de REL2 NO FUE INSERTADO<BR>";
        if ($model->insertElement('REL4',"ELEM1-1#ELEM2-2#ELEM3-3#ELEM4-4",$debug)<0)
            $a=$a."Elemento de REL2 NO FUE INSERTADO<BR>";
        if ($model->insertElement('REL22',"ELEM3-3#ELEM4-4",$debug)<0)
            $a=$a."Elemento de REL2 NO FUE INSERTADO<BR>";

    $tiempo=$timer->end_timer();
    echo " | TERMINADO. TIEMPO: $tiempo <BR>";
    echo " DETALLES DE LOS ELEMENTOS NO INSERTADOS: $a<BR>";

    echo "RELLENANDO DATOS DE LOS ELEMENTOS<BR>";
    $timer->start_timer();
    $model->setValue("/ELEM1-1/ATRB1", "**VALOR**", $debug);
    $model->setValue("/ELEM2-2/ATRB1", "**VALOR**", $debug);
    $model->setValue("/ELEM3-3/ATRB1", "**VALOR**", $debug);
    $model->setValue("/ELEM4-4/NODO2/NODO1/NODO1/ATR1", "**VALOR**", $debug);
    $model->setValue("/ELEM1-1/ERRONEO", "**VALOR**", $debug);
    $model->setValue("/ELEM2-2/NODOELEM/ATRB1", "**VALOR**", $debug);
    $model->setValue("/ELEM3-3", "**VALOR**", $debug);
    $model->setValue("/ELEM4-4", "**VALOR**", $debug);

    $model->setValue("/ELEM1-1#ELEM2-2/ATR1", "**VALOR**", $debug);
    $model->setValue("/ELEM1-1#ELEM2-2#ELEM3-3/ATR1", "**VALOR**", $debug);
    $model->setValue("/ELEM1-1#ELEM2-2#ELEM3-3/ATR1", "**VALOR**", $debug);
    $model->setValue("/ELEM1-1#ELEM2-2#ELEM3-3#ELEM4-4/NODO2/NODO1/NODO1/ATR1", "**VALOR**", $debug);
    $model->setValue("/ELEM3-3#ELEM4-4/ATR1", "**VALORXX**", $debug);

   $tiempo=$timer->end_timer();
    echo "| TERMINADO. TIEMPO: $tiempo <BR>";


    echo "RECUPERANDO VALORES INSERTADOS<BR>";
$timer->start_timer();
    $model->getValue("/ELEM1-1/ATRB1",true);
    $model->getValue("/ELEM2-2/ATRB1",true);
    $model->getValue("/ELEM3-3/ATRB1",true);
    $model->getValue("/ELEM4-4/NODO2/NODO1/NODO1/ATR1",true);
    $model->getValue("/ELEM1-1/ERRONEO",true);
    $model->getValue("/ELEM2-2/NODOELEM/ATRB1",true);
    $model->getValue("/ELEM3-3",true);
    $model->getValue("/ELEM4-4",true);
    $model->getValue("/ELEM3-3#ELEM4-4/ATR1",true);
$tiempo=$timer->end_timer();

echo "| TERMINADO. TIEMPO: $tiempo <BR>";


echo "ELIMINANDO ALGUNOS VALORES DE ATRIBUTOS <BR>";
$timer->start_timer();
    $model->deleteValue("/ELEM3-3", true);
    $model->getValue("/ELEM3-3", true);
    $model->deleteValue("/ELEM2-2/NODOELEM/ATRB1", true);
    $model->getValue("/ELEM2-2/NODOELEM/ATRB1", true);
    $model->deleteValue("/ELEM1-1#ELEM2-2#ELEM3-3/ATR1",true);
    $model->getValue("/ELEM1-1#ELEM2-2#ELEM3-3/ATR1",true);
$tiempo=$timer->end_timer();
echo "| TERMINADO. TIEMPO: $tiempo <BR>";


echo "ELIMINANDO ELEMENTOS COMPLETOS <BR>";
$timer->start_timer();
    $model->deleteElement("ELEM3-3#ELEM4-4", true);
    $model->getValue("/ELEM3-3#ELEM4-4/ATR1",true);
    $model->deleteElement("ElementoTipo3", true);
    $model->deleteElement("ELEM1-1#ELEM2-2#ELEM3-3", true);
    $model->deleteElement("ELEM4-2#ELEM4-4", true);
$tiempo=$timer->end_timer();
echo "| TERMINADO. TIEMPO: $tiempo <BR>";
/*
    $model->setValue("/ELEM1-1#ELEM2-2", "", $debug);
    $model->setValue("/ELEM1-1#ELEM2-2#ELEM3-3", "", $debug);
    $model->setValue("/ELEM1-1#ELEM2-2#ELEM3-3#ELEM4-4", "", $debug);
    $model->setValue("/", "", $debug);
    $model->setValue("/", "", $debug);
*/

/*

$model->insertElement($nombreE,$tipoE,$debug);

    $model->insertElement($nombreE,$tipoE,$debug);


    $model->setValue($nombreV,$valorV,$debug);
            $model->getValue($nombreV,$debug);

            $model->deleteValue();

            $model->deleteElement();
            $model->getId();



            //CHAPUCEANDO
            $model->addChild('ELEM',"element","","",$debug);
            $model->addChild('ATRIBUTO',"integer","/ELEM","",$debug);
            $model->addChild('TRIPLE',"element#3","","",$debug);
            $model->addChild('ATRIBUTO',"integer","/TRIPLE","",$debug);

            $model->addChild('DOBLE',"element#2","","",$debug);
            $model->addChild('ATRIBUTO',"integer","/DOBLE","",$debug);

            muestraArbol();
            $id1=$model->insertElement('USR',"Usuario1",$debug);
            $id2=$model->insertElement('RSC',"Recurso1",$debug);
            $id3=$model->insertElement('ELEM',"Elem1",$debug);
            $id4=$model->insertElement('TRIPLE',"USR-$id1#RSC-$id2#ELEM-$id3",$debug);
            $id4=$model->insertElement('DOBLE',"USR-$id1#RSC-$id2",$debug);

            $model->setValue("/USR-$id1#RSC-$id2#ELEM-$id3/ATRIBUTO",'YEEEEEHA',$debug);
            $model->setValue('/USR-1#RSC-2#ELEM-3/ATRIBUTO','YEEEEEHA',$debug);

            $model->setValue("/USR-$id1#RSC-$id2#ELEM-$id3/ATRIBUTO",'YEEEEEHA3',$debug);
            $model->setValue("/USR-$id1#RSC-$id2/ATRIBUTO",'YEEEEEHA2',$debug);



*/
}

dB::close($link);

?>
    </body>
</html>
